package com.loong.member.controller.forehead;

import com.loong.common.enumerate.ResultCode;
import com.loong.common.exception.GlobalException;
import com.loong.common.mvc.BaseForeheadController;
import com.loong.common.param.BaseIdParam;
import com.loong.common.rest.Result;
import com.loong.common.validator.group.CommonValidate;
import com.loong.global.dto.UserDTO;
import com.loong.member.common.forehead.param.*;
import com.loong.member.handler.CartHandler;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @Description: 处理购物车请求的Controller
 * @Author: 刘群
 * @Date: 2020/10/23 17:19
 */
@RestController
@RequestMapping("forehead/member/cart")
public class CartController extends BaseForeheadController {

    @Resource
    private CartHandler cartHandler;

    /**
     * 查询购物车集合
     * @return 结果
     */
    @PostMapping("queryCartList")
    public Result queryCartListByUserId(@ModelAttribute(value = "userInfo", binding = false) UserDTO userDTO){
        return handlerExecutor.execute(() -> cartHandler.foreheadQueryCartListByUserId(userDTO.getId()));
    }

    /**
     * 查询单个购物车
     * @param param 商家id封装的参数
     * @return 结果
     */
    @PostMapping("query")
    public Result queryCartByParam(@RequestBody @Validated({CommonValidate.class})CartQueryForeheadParam param,@ModelAttribute(value = "userInfo", binding = false) UserDTO userDTO){
        param.setUserId(userDTO.getId());
        return handlerExecutor.execute(() -> cartHandler.foreheadQuerySingleCart(param));
    }

    /**
     * 根据用户id统计用户所有购物车中的商品数量
     * @return 结果
     */
    @PostMapping("getGoodsNum")
    public Result getGoodsNumInUserCarts(@ModelAttribute(value = "userInfo", binding = false) UserDTO userDTO){
        return handlerExecutor.execute(() -> cartHandler.foreheadCalculateGoodsNumInUserCarts(userDTO.getId()));
    }

    /**
     * 删除购物车
     * @param param 购物车id集合
     * @return 结果
     */
    @PostMapping("deleteCarts")
    public Result deleteCarts(@RequestBody @Validated({CommonValidate.class}) CartDeleteForeheadParam param,@ModelAttribute(value = "userInfo", binding = false) UserDTO userDTO){
        param.setUserId(userDTO.getId());
        return handlerExecutor.execute(() -> cartHandler.foreheadDeleteCarts(param));
    }

    /**
     * 新增购物车和购物车下所有的购物详情到数据库
     * @param param 购物车和购物详情集合封装的参数
     * @return 结果
     */
    @PostMapping("saveCartAndCartItems")
    public Result saveCartAndCartItems(@RequestBody @Validated({CommonValidate.class}) CartAndCartItemForeheadParam param,@ModelAttribute(value = "userInfo", binding = false) UserDTO userDTO){
        param.getCartParam().setUserId(userDTO.getId());
        return handlerExecutor.execute(() -> cartHandler.foreheadSaveCartAndCartItem(param));
    }
}
